import { fromJS } from 'immutable';
import { Utils } from 'fe-lib';
import { apiStatus, pageResultParser } from 'shared/utils/reducerUtil';
import * as actionTypes from '../consts';

const { createReducer } = Utils;
const { datas } = actionTypes.key;
const initialState = fromJS({
  /** 属性数据初始化 */
  // [{id:'',name:'',type:'dept|user'},isLeaf:true]
  [datas]: {
    /** 属性数据状态，请参考  apiStatus */
    status: apiStatus.init,
    /** 当前状态对应的消息：错误消息或者加载中的文本等 */
    message: '',
    /** 数据对象，根据实际情况决定这里是{}or[{},{}] */
    data: {
      filter: {},
      pager: { page: 1, pageSize: 10, total: 0 },
      dataList: []
    },
  }
});

const handlers = {
  [actionTypes.getDatas](state, { payload, error, meta }) {
    /** 获取旧的apiState */
    const apiState = state.get(datas);
    /** 调用工具方法update获取新的apiState */
    const newApiState = pageResultParser(apiState, { payload, error, meta });
    /** 把新的apiState设置到state，并返回给上层函数 */
    return state.set(datas, newApiState);
  },
};

export default createReducer(initialState, handlers);
